package top.yqingyu.trans$client.api;

import top.yqingyu.qymsg.MsgTransfer;
import top.yqingyu.qymsg.QyMsg;

import java.io.IOException;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.concurrent.locks.ReentrantLock;

public class Connection {
    public volatile Socket socket;
    public volatile ConnectionConfig config;
    public volatile boolean isClose;
    public volatile LocalDateTime activeTime;
    public ReentrantLock lock = new ReentrantLock();

    public static Connection getInstance(ConnectionConfig config) throws Exception {
        Connection c = new Connection();
        c.socket = GetSocket.get(config);
        c.config = config;
        return c;
    }


    public QyMsg get(QyMsg msg) throws Exception {
        try {
            lock.lock();
            send(msg);
            return receive();
        } finally {
            activeTime = LocalDateTime.now();
            lock.unlock();
        }
    }

    public QyMsg get(QyMsg msg, int timeout) throws Exception {
        try {
            lock.lock();
            send(msg);
            return receive(timeout);
        } finally {
            lock.unlock();
        }
    }


    public void send(QyMsg msg) throws Exception {
        try {
            config.msgTransfer.writeQyMsg(socket, msg);
        } catch (Exception e) {
            close();
            throw e;
        }
    }

    public QyMsg receive(int timeout) throws Exception {
        try {
            return config.msgTransfer.readMsg(socket, timeout);
        } catch (Exception e) {
            close();
            throw e;
        }
    }

    public QyMsg receive() throws Exception {
        try {
            return config.msgTransfer.readQyMsg(socket, config.RUNNING);
        } catch (Exception e) {
            close();
            throw e;
        }
    }

    public void sendHeartPacket() throws Exception {
        lock.lock();
        try {
            send(config.HEART_BEAT_MSG);
        } finally {
            lock.unlock();
        }
    }

    public boolean testSocket() {
        try {
            socket.sendUrgentData(0xFF);
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    public void close() {
        isClose = true;
    }
}
